package top.yaofengqiao.springcloudsimple.web.starter.aop;

import cn.hutool.core.text.CharSequenceUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.yaofengqiao.springcloudsimple.common.constant.CommonConstant;
import top.yaofengqiao.springcloudsimple.common.util.PageParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yfq
 * @date 11:12
 * @description
 */
@Aspect
public class PageParamAspect {
    @Pointcut("execution(public * top.yaofengqiao.springcloudsimple.*.biz.trigger.http.*.*(..))")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object handler(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (!(arg instanceof PageParam)) continue;

            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                HttpServletRequest request = requestAttributes.getRequest();

                String pageStr = request.getParameter(CommonConstant.PAGE);
                String sizeStr = request.getParameter(CommonConstant.SIZE);
                long page = CharSequenceUtil.isEmpty(pageStr) ? 1 : Long.parseLong(pageStr);
                long size = CharSequenceUtil.isEmpty(sizeStr) ? 10 : Long.parseLong(sizeStr);

                PageParam pageParam = (PageParam) arg;
                pageParam.setPage(page);
                pageParam.setSize(size);
            }
        }

        return joinPoint.proceed();
    }
}
